package com.jindi.jacococli.biz.business.service;

import com.jindi.jacococli.biz.constant.Constant;
import com.jindi.jacococli.biz.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import static com.jindi.jacococli.biz.constant.Constant.NICK_NAME;

/**
 * 邮件发送service
 */
@Service
public class MailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MailService.class);

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private MailProperties mailProperties;

    // 发送带附件的邮件
    public boolean sendEmailWithAttachment(String to, String filePath) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getUsername(), NICK_NAME);
            helper.setTo(to);
            helper.setSubject(Constant.EMAIL_SUBJECT);
            helper.setText(String.format(Constant.EMAIL_CONTENT, filePath, filePath, DateUtils.nowDateTimeString()), true); // true 表示内容是 HTML 格式
            mailSender.send(mimeMessage);
            return true;
        } catch (Exception e) {
            LOGGER.error("send email error", e);
        }
        return false;
    }
}
